package com.qianguo.sender;

import android.content.Context;
import android.text.TextUtils;

import com.eva.androidlibrary.api.entity.UserInfo;
import com.eva.androidlibrary.utils.FileUtil;
import com.eva.androidlibrary.utils.JsonParser;
import com.eva.androidlibrary.utils.SharedPreferencesHelper;
import com.qianguo.sender.api.entity.SenderUserInfo;
import com.qianguo.sender.base.App;

/**
 * Class description
 *
 * @author GUXIA318
 * @date 2015-09-23 15:48
 */
public class UserManager {

    private static final String USER_CACHE_FILE_NAME = "user.txt";
    private static final String KEY_USER = "key_user";

    /**
     * 更新用户信息
     *
     * @param app
     * @param user
     */
    public static void updateUser(App app, SenderUserInfo user) {
        SenderUserInfo curUser = app.getUser();
        curUser.setEmail(user.getEmail());
        curUser.setPhone(user.getPhone());
        saveUser(app, curUser);
    }

    /**
     * 保存用户信息
     *
     * @param app
     * @param user
     */
    public static void saveUser(App app, SenderUserInfo user) {
        SharedPreferencesHelper.getInstance(app)
                .putString(KEY_USER, JsonParser.toJSONString(user));
//        String path = getUserCache(app.getApplicationContext());
//        File file = new File(path);
//        FileUtil.write(file, JsonParser.toJSONString(user));
        // 修改全局用户
        app.setUser(user);
    }

    /**
     * 获取用户信息
     *
     * @param context
     * @return
     */
    public static SenderUserInfo getUser(Context context) {
        SharedPreferencesHelper helper = SharedPreferencesHelper.getInstance(context);
        String jsonUser = helper.getString(KEY_USER);
        if (TextUtils.isEmpty(jsonUser)) {
            return null;
        }
        return JsonParser.parseObject(jsonUser, SenderUserInfo.class);
//        String path = getUserCache(context);
//        File file = new File(path);
//
//        if (!file.exists()) {
//            return null;
//        }
//        String userStr = FileUtil.read(file);
//        return JsonParser.parseObject(userStr, UserInfo.class);
    }

    /**
     * 获取用户缓存目录
     *
     * @param context
     * @return
     */
    private static String getUserCache(Context context) {
        return FileUtil.getFileDir(context) + "/" + USER_CACHE_FILE_NAME;
    }
}
